package cat.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 用于上传图片
 * @ResponseBody 这个注解表示返回的内容要转成json格式
 * 要在toncat中做如下映射
 * <Context debug="0" docBase="D:/imguploads" path="/uploads" reloadable="true"/>
 */
@Controller @ResponseBody
public class UploadFileController {
    @RequestMapping(value="/article/uploadimg")
    public String uploadFile(MultipartHttpServletRequest request) throws IllegalStateException, IOException {
        //imgFile 这个名称没有什么理由 kindeditor 就是这么写的
        MultipartFile file =request.getFile("imgFile");

        //生成一个随机的文件名
        String  newName= UUID.randomUUID().toString();
        File destFile=new File("/imguploads/"+newName);
        file.transferTo(destFile);

        //这个图片的地址,一定要返回前台(kindeditor) ,它要以json的格式返回
        String path="http://localhost:8080/uploads/"+newName;

        return "{\"error\":0,\"url\":\""+path+"\"}";
    }
}
